package com.guet.utils;


import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

@Component
public class RedisID {
    /**
     * 开始时间戳: 2022-1-1 北京时间8点
     */
    private static final long BEGIN_TIMESTAMP = 1640995200L;
    /**
     * 序列化的位数
     */
    private static final int COUNT_BITS = 32;
    private final StringRedisTemplate stringRedisTemplate;
    public RedisID(StringRedisTemplate stringRedisTemplate){
        this.stringRedisTemplate = stringRedisTemplate;
    }

    /**
     * 共64位
     * 由三部分组成: 符号位1 + 时间戳31 + 序列号32
     * 时间戳单位是秒
     * @param keyPrefix
     */
    public long nextId(String keyPrefix){
        // 时间戳差值
        LocalDateTime now = LocalDateTime.now();
        long nowTimeStamp = now.toEpochSecond(ZoneOffset.ofHours(8));
        long gap = nowTimeStamp - BEGIN_TIMESTAMP;

        // 当天的日期(一天用一个key,redis单个key的自增长的上限是2^64,生成的ID中序列号只占32位,所以不能一直只用一个key)
        String date = now.format(DateTimeFormatter.ofPattern("yyyy:MM:dd"));
        // key不存在会自动创建,并赋值为1
        long count = stringRedisTemplate.opsForValue().increment("icr:" + keyPrefix + ":" + date);

        return (gap << COUNT_BITS) | count;
    }
}
